package com.wonders.bigdata.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * Description: <br>
 *
 * @author: XB
 * @date: 2021/5/11 10:53
 */
public class GroupChatClient {
    // 定义相关的属性
    private static final String HOST = "127.0.0.1";// 服务器的IP
    private static final int PORT = 6667;// 服务器的端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String userName;

    public GroupChatClient() throws IOException {
        // 创建选择器
        selector = Selector.open();
        // 初始化通道
        socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", PORT));
        // 设置为非阻塞
        socketChannel.configureBlocking(false);
        // 注册为读事件
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 获取当前客户端名称
        userName = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(userName + " is ok...");
    }

    /**
     * 向服务器发送消息
     * @param info
     */
    public void sendInfo(String info) {
        info = userName + " 说：" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取服务器返回的消息
     */
    public void readInfo() {
        try {
            // 通过阻塞查询服务器是否有事件请求
            int count = selector.select();
            if (count > 0) {
                // 有可用的通道
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        // 得到相关的通道
                        SocketChannel sc = (SocketChannel)key.channel();
                        // 得到一个buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        // 读取
                        sc.read(buffer);
                        // 把读取到的缓冲区数据转成字符串
                        String mas = new String(buffer.array());
                        System.out.println(mas.trim());
                    }
                    iterator.remove();
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        // 启动我们的客户端
        GroupChatClient chatClient = new GroupChatClient();

        // 启动一个线程, 每隔3秒，读取从服务器发送数据
        new Thread(){
            public void run() {
                while (true) {
                    chatClient.readInfo();
                    try {
                        sleep(3000L);
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        // 发送数据给服务端
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }

    }

}
